Send Keys in Selenium
Send Keys is a Selenium WebDriver method used to enter text or send keyboard input to a web element such as a text box, search field, username field, password field, textarea, or other editable input element. It allows automation scripts to simulate the action of a user typing characters into a web page.
In Selenium Java automation, the sendKeys() method is commonly used with the WebElement interface. It is an important part of browser automation because many real-world test cases require entering data into forms, searching for products, logging into applications, filling registration forms, and interacting with keyboard-based controls.
JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, web elements, browser automation, Java, TestNG, framework development, and practical automation testing. Learn more about Selenium Training at JustAcademy.
You can also explore the course demo through Register for Selenium Course Demo.
1. What is Send Keys?
The sendKeys() method is used to send keyboard input to a Selenium WebElement. It can enter normal text, numbers, symbols, spaces, and special keyboard keys depending on the requirement.
For example, suppose a web page contains a username field:
<input type="text" id="username">
Selenium can locate this element and enter a username using:
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
The automation performs an action similar to a user clicking inside the field and typing admin.
2. Why is sendKeys() Used in Selenium?
Web applications contain many input fields that require data entry. Manually entering this information during every test execution is time-consuming. Selenium's sendKeys() method allows these actions to be automated.
- Entering usernames
- Entering passwords
- Entering search keywords
- Filling registration forms
- Entering email addresses
- Entering phone numbers
- Entering addresses
- Entering comments in textareas
- Entering product search terms
- Uploading files using file input elements
- Sending keyboard shortcuts
- Clearing and replacing existing input values
3. Basic Syntax of sendKeys()
The basic syntax is:
element.sendKeys("text");
Example:
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Selenium WebDriver");
Here:
- element represents the WebElement.
- sendKeys() is the WebElement method.
- "Selenium WebDriver" is the text sent to the element.
4. How sendKeys() Works
The general flow of using sendKeys() is:
Open Browser
↓
Open Web Application
↓
Locate Web Element
↓
Store Element in WebElement
↓
Call sendKeys()
↓
Send Text/Keyboard Input
↓
Input Appears in Web Page
↓
Continue Test Execution
5. Example of sendKeys() with ID Locator
Suppose the HTML is:
<input type="text" id="username" placeholder="Enter username">
Selenium code:
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("john");
This code locates the username field using its ID and enters the value john.
6. Send Keys with Name Locator
Example HTML:
<input type="text" name="email">
Java code:
WebElement email = driver.findElement(By.name("email"));
email.sendKeys("[email protected]");
7. Send Keys with CSS Selector
sendKeys() can be used with any locator that returns a WebElement.
WebElement searchBox = driver.findElement(By.cssSelector("#search"));
searchBox.sendKeys("Selenium");
Another example:
WebElement email = driver.findElement(By.cssSelector("input[name='email']"));
email.sendKeys("[email protected]");
8. Send Keys with XPath
XPath can also be used to locate the input element.
WebElement username = driver.findElement(By.xpath("//input[@id='username']"));
username.sendKeys("admin");
Using placeholder:
WebElement search = driver.findElement(By.xpath("//input[@placeholder='Search']"));
search.sendKeys("Selenium WebDriver");
9. Complete Login Example Using sendKeys()
A common Selenium automation scenario is login testing.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LoginTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.sendKeys("admin");
password.sendKeys("admin123");
driver.findElement(By.id("login")).click();
driver.quit();
}
}
In this example, sendKeys() enters values into both the username and password fields, while click() submits the login form.
10. Sending Numbers Using sendKeys()
Numbers can also be entered using sendKeys().
WebElement age = driver.findElement(By.id("age"));
age.sendKeys("25");
Even though the value represents a number, Selenium generally sends keyboard input as a character sequence.
11. Sending Special Characters
sendKeys() can enter special characters supported by the input field.
WebElement input = driver.findElement(By.id("input"));
input.sendKeys("Hello @123!");
Example:
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");
12. Sending Space Between Words
Spaces can be included directly inside the string.
WebElement search = driver.findElement(By.id("search"));
search.sendKeys("Selenium WebDriver Tutorial");
13. Sending Multiple Words
Multiple words can be sent as a single string.
WebElement address = driver.findElement(By.id("address"));
address.sendKeys("Mumbai Maharashtra India");
14. Using Keyboard Keys with sendKeys()
Selenium provides the Keys class for special keyboard keys such as ENTER, TAB, ESCAPE, CONTROL, SHIFT, ARROW keys, BACK_SPACE, DELETE, and others.
Import the Keys class:
import org.openqa.selenium.Keys;
Example:
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Selenium", Keys.ENTER);
This enters Selenium into the search field and then sends the ENTER key.
15. Using ENTER with sendKeys()
ENTER is frequently used when automating search boxes and forms.
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver", Keys.ENTER);
This can simulate entering a search term and pressing Enter.
16. Using TAB with sendKeys()
The TAB key can move focus from one element to another.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin", Keys.TAB);
After entering the username, the TAB key moves focus to the next focusable element.
17. Using BACK_SPACE
BACK_SPACE can be used to remove characters from an input field.
WebElement input = driver.findElement(By.id("username"));
input.sendKeys("admin");
input.sendKeys(Keys.BACK_SPACE);
For more controlled clearing, clear() is usually easier when the requirement is to remove the complete existing value.
18. Using DELETE
The DELETE key can also be sent to an element.
WebElement input = driver.findElement(By.id("username"));
input.sendKeys(Keys.DELETE);
19. Using ARROW Keys
Selenium allows keyboard navigation using arrow keys.
WebElement input = driver.findElement(By.id("input"));
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ARROW_UP);
These keys can be useful when testing keyboard-driven components.
20. Using CONTROL with sendKeys()
CONTROL can be used for keyboard shortcuts.
WebElement input = driver.findElement(By.id("input"));
input.sendKeys(Keys.CONTROL, "a");
This commonly represents the keyboard action Ctrl + A, which selects the text in the focused input.
21. Select All Text Using CTRL + A
A common automation requirement is selecting all existing text before replacing it.
WebElement username = driver.findElement(By.id("username"));
username.click();
username.sendKeys(Keys.CONTROL, "a");
username.sendKeys("newUser");
The general flow is:
Click Input
↓
CTRL + A
↓
Select Existing Text
↓
Type New Value
22. CTRL + C and CTRL + V
Keyboard shortcuts can also be sent through sendKeys().
WebElement input = driver.findElement(By.id("input"));
input.sendKeys(Keys.CONTROL, "a");
input.sendKeys(Keys.CONTROL, "c");
For clipboard-dependent automation, behavior can depend on the operating system, browser, permissions, and test environment, so such tests should be designed carefully.
23. sendKeys() with clear()
The clear() method removes the existing value from an editable field, while sendKeys() enters a new value.
WebElement username = driver.findElement(By.id("username"));
username.clear();
username.sendKeys("newUser");
This is a common pattern when a field may already contain data.
24. clear() vs sendKeys()
| Method | Purpose | Example |
| clear() | Removes existing input value | element.clear() |
| sendKeys() | Enters text or keyboard input | element.sendKeys("Hello") |
| click() | Clicks an element | element.click() |
25. sendKeys() with Textarea
sendKeys() is not limited to single-line input fields. It can also be used with textarea elements.
Example HTML:
<textarea id="comments"></textarea>
Java:
WebElement comments = driver.findElement(By.id("comments"));
comments.sendKeys("This is an automated test comment.");
26. sendKeys() with Login Form
Login automation commonly uses sendKeys() for username and password fields.
WebElement username = driver.findElement(By.name("username"));
WebElement password = driver.findElement(By.name("password"));
username.sendKeys("testuser");
password.sendKeys("Test@123");
27. sendKeys() with Registration Form
Registration forms normally contain several input fields.
driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Smith");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("phone")).sendKeys("9876543210");
This approach can automate repetitive form-filling activities.
28. sendKeys() with Search Box
Search functionality is one of the most common use cases.
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Laptop");
searchBox.sendKeys(Keys.ENTER);
The automation enters the search keyword and submits the search using ENTER.
29. sendKeys() with Dynamic Web Elements
Modern web applications frequently generate elements dynamically. The important point is that sendKeys() requires a valid WebElement before input can be sent.
A typical approach is:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement searchBox = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("search"))
);
searchBox.sendKeys("Selenium");
This approach waits for the required element to become visible before sending input.
30. sendKeys() with Explicit Wait
Explicit waits are useful when an element may not be immediately available.
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.elementToBeClickable(By.id("username"))
);
username.sendKeys("admin");
Waiting before interacting can make automation more reliable when pages load asynchronously.
31. sendKeys() and ElementToBeClickable
If an input field needs to be interactable before typing, elementToBeClickable() can be used.
WebElement search = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.id("search")));
search.sendKeys("Selenium");
32. sendKeys() and Visibility
An element that is present in the DOM may not necessarily be visible to the user. A visibility wait can be useful before entering data.
WebElement input = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.visibilityOfElementLocated(By.id("input")));
input.sendKeys("Test Data");
33. Sending Text Directly Without Creating a Variable
A WebElement variable is not mandatory if the interaction is simple.
driver.findElement(By.id("username")).sendKeys("admin");
This is concise and useful for simple test cases.
34. Using WebElement Variable
For reusable or complex automation, storing the element in a variable can improve readability.
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.sendKeys("admin");
35. sendKeys() in Page Object Model
In a Page Object Model framework, sendKeys() is commonly placed inside page classes so that test classes can use meaningful methods.
public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
private By password = By.id("password");
private By loginButton = By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(username).sendKeys(value);
}
public void enterPassword(String value) {
driver.findElement(password).sendKeys(value);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}
Test class:
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
loginPage.enterPassword("admin123");
loginPage.clickLogin();
36. Parameterized sendKeys() Method
Parameterized methods allow the same page method to enter different values during different tests.
public void enterUsername(String usernameValue) {
driver.findElement(By.id("username")).sendKeys(usernameValue);
}
Usage:
loginPage.enterUsername("user1");
loginPage.enterUsername("user2");
37. sendKeys() in TestNG
sendKeys() can be used inside TestNG test methods.
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test
public void loginTest() {
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("login")).click();
}
}
38. Data-Driven Testing with sendKeys()
In data-driven testing, values can be supplied from test data and passed to sendKeys().
String username = "testuser";
String password = "Test@123";
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
In a larger framework, the values may come from Excel, CSV, JSON, databases, configuration files, or TestNG data providers.
39. sendKeys() with TestNG DataProvider
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"user1", "pass1"},
{"user2", "pass2"},
{"user3", "pass3"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
}
40. File Upload Using sendKeys()
For an HTML file input element, Selenium can commonly upload a file by sending the file path to the input element.
Example HTML:
<input type="file" id="fileUpload">
Java:
WebElement upload = driver.findElement(By.id("fileUpload"));
upload.sendKeys("C:\\Users\\Admin\\Documents\\test.pdf");
Unlike normal text entry, the value sent to a file input is a local file path.
41. File Upload Best Practice
Use a valid absolute path or an appropriately resolved project path for the test environment.
String filePath = "C:\\TestFiles\\sample.pdf";
driver.findElement(By.id("fileUpload")).sendKeys(filePath);
Hard-coded machine-specific paths can create portability problems when tests run on another computer or CI server.
42. sendKeys() with Auto-Suggestion Fields
Auto-suggestion fields often require text entry followed by waiting for suggestions.
WebElement city = driver.findElement(By.id("city"));
city.sendKeys("Mumbai");
After entering the text, the test may need to wait for the suggestion list and select the required option.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement suggestion = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[contains(text(),'Mumbai')]")
)
);
suggestion.click();
43. sendKeys() with Date Fields
Some applications allow date input directly into text fields.
WebElement date = driver.findElement(By.id("date"));
date.sendKeys("25/09/2026");
The correct format depends on the application and the HTML control. Date inputs may behave differently from ordinary text fields, so the expected input format should be verified before automating them.
44. sendKeys() with Read-Only Fields
If an input element is read-only, sendKeys() may not be able to modify it normally.
WebElement input = driver.findElement(By.id("readonlyField"));
input.sendKeys("Test");
If the field is intentionally read-only, the test should interact with the application's supported UI workflow instead of forcing a value into the element.
45. sendKeys() with Disabled Fields
A disabled input element cannot normally receive user input.
WebElement input = driver.findElement(By.id("disabledField"));
input.sendKeys("Test");
Such an interaction can result in an exception because the element is not interactable.
46. Common Exceptions with sendKeys()
Several Selenium exceptions can occur when sendKeys() is used incorrectly or when the application is not ready for interaction.
| Exception | Possible Reason |
| ElementNotInteractableException | Element cannot currently receive keyboard input |
| ElementClickInterceptedException | Another element may be blocking interaction |
| NoSuchElementException | Locator could not find the element |
| StaleElementReferenceException | Element reference is no longer attached to the current DOM |
| TimeoutException | Explicit wait condition was not satisfied within the timeout |
| InvalidElementStateException | Element is in a state that does not allow the requested operation |
47. ElementNotInteractableException
This exception can occur when the element exists but cannot currently receive input.
Possible causes include:
- Element is hidden.
- Element is disabled.
- Element is not ready for interaction.
- Another UI state prevents interaction.
- The wrong element was located.
A suitable explicit wait and correct locator can help when timing or element state is the problem.
48. NoSuchElementException
This exception means Selenium could not locate the requested element.
Check:
- Locator correctness.
- Page URL.
- DOM structure.
- Element availability.
- Iframe context.
- Dynamic content loading.
49. StaleElementReferenceException
A previously located WebElement can become stale when the page or DOM is refreshed or updated.
Instead of continuing to use an old reference, locate the element again when appropriate.
WebElement input = driver.findElement(By.id("username"));
input.sendKeys("admin");
If the page dynamically recreates the element, the locator may need to be executed again after the DOM update.
50. sendKeys() and Iframes
If the input field is inside an iframe, Selenium must switch into that iframe before locating and interacting with the element.
driver.switchTo().frame("paymentFrame");
WebElement cardNumber = driver.findElement(By.id("cardNumber"));
cardNumber.sendKeys("4111111111111111");
driver.switchTo().defaultContent();
The important sequence is:
Switch to iframe
↓
Locate input element
↓
sendKeys()
↓
Perform required action
↓
Switch back to main document
51. sendKeys() and Multiple Windows
If the input element is located in another browser window or tab, Selenium must first switch to the correct window.
String parentWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
driver.findElement(By.id("search")).sendKeys("Selenium");
52. sendKeys() and Shadow DOM
Modern web applications may use Shadow DOM. In such cases, ordinary locators may not directly locate elements inside a shadow root. The test must use the appropriate Shadow DOM access supported by the application and Selenium version.
53. sendKeys() with Actions Class
The Selenium Actions class can be used for more advanced keyboard interactions.
Actions actions = new Actions(driver);
actions.sendKeys("Selenium").perform();
The Actions API is useful when keyboard input needs to be performed as part of a more complex user interaction sequence.
54. WebElement.sendKeys() vs Actions.sendKeys()
| Feature | WebElement.sendKeys() | Actions.sendKeys() |
| Main Purpose | Send input directly to a WebElement | Perform advanced keyboard interactions |
| Typical Usage | Text fields and textareas | Keyboard sequences and complex interactions |
| Example | element.sendKeys("Hello") | actions.sendKeys("Hello").perform() |
| Target | Specific WebElement | Current focus or specified interaction target |
55. Complete Practical Example
The following example demonstrates opening a page, locating fields, clearing existing data, entering values, and submitting the form.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SendKeysExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement searchBox = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("search")
)
);
searchBox.clear();
searchBox.sendKeys("Selenium WebDriver");
searchBox.sendKeys(Keys.ENTER);
} finally {
driver.quit();
}
}
}
56. Real-World E-Commerce Example
Consider an e-commerce application where a tester needs to search for a product.
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.clear();
searchBox.sendKeys("Laptop");
searchBox.sendKeys(Keys.ENTER);
Possible automation flow:
Open E-Commerce Website
↓
Locate Search Box
↓
Clear Existing Text
↓
Enter "Laptop"
↓
Press ENTER
↓
Search Results Displayed
↓
Validate Search Results
57. Real-World Registration Example
driver.findElement(By.id("firstName")).sendKeys("Rahul");
driver.findElement(By.id("lastName")).sendKeys("Sharma");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("phone")).sendKeys("9876543210");
driver.findElement(By.id("address")).sendKeys("Mumbai, Maharashtra");
After entering the data, the test can validate the entered values and submit the form.
58. Best Practices for sendKeys()
- Use stable and meaningful locators.
- Prefer explicit waits when the application is dynamic.
- Use clear() before sendKeys() when replacing an existing value.
- Keep test data separate from test logic in framework-based automation.
- Use Page Object Model for maintainable automation frameworks.
- Use parameterized methods for reusable input operations.
- Validate important input fields after entering data.
- Avoid unnecessary Thread.sleep() calls.
- Handle iframe context correctly when fields are inside frames.
- Use appropriate keyboard keys for keyboard-driven interactions.
- Keep environment-specific file paths configurable.
- Capture useful logs when input-related failures occur.
59. Common Mistakes While Using sendKeys()
- Using an incorrect locator.
- Trying to type into a hidden element.
- Trying to type into a disabled element.
- Ignoring iframe context.
- Using stale WebElement references.
- Typing before the page is ready.
- Not clearing existing data when replacement is required.
- Using machine-specific file paths for file uploads.
- Assuming every input field accepts the same date or number format.
- Using keyboard shortcuts without ensuring the correct element has focus.
60. Troubleshooting sendKeys()
| Problem | What to Check |
| Text is not entered | Check locator, visibility, enabled state, and element readiness |
| NoSuchElementException | Verify locator and current page/frame |
| ElementNotInteractableException | Check whether the element is visible and enabled |
| StaleElementReferenceException | Locate the element again after DOM changes |
| Text goes into wrong field | Verify locator uniqueness and active element |
| Keyboard shortcut fails | Check focus and use the appropriate Keys value |
| File upload fails | Verify input type and file path |
| Input happens too early | Use an appropriate explicit wait |
61. Advantages of sendKeys()
- Simple API for entering text.
- Useful for automating forms.
- Supports keyboard keys through the Keys class.
- Works with many types of editable web elements.
- Can be combined with waits and Page Object Model.
- Useful for login, registration, search, checkout, and other workflows.
- Supports file-path input for suitable file upload controls.
62. Limitations and Considerations
- The target element must be suitable for keyboard input.
- Hidden or disabled elements may reject input.
- Dynamic pages may require synchronization.
- Iframe elements require correct frame switching.
- Special application controls may require Actions or another interaction strategy.
- Keyboard behavior can vary depending on browser, operating system, and application implementation.
63. Interview Questions on sendKeys()
Q1. What is sendKeys() in Selenium?
sendKeys() is a WebElement method used to send text and keyboard input to an editable web element.
Q2. Which interface provides sendKeys()?
The sendKeys() method is provided by Selenium's WebElement interface.
Q3. How do you enter text into a textbox?
driver.findElement(By.id("username")).sendKeys("admin");
Q4. How do you press ENTER using Selenium?
element.sendKeys(Keys.ENTER);
Q5. How do you clear a textbox before entering new data?
element.clear();
element.sendKeys("New Value");
Q6. Can sendKeys() be used for file upload?
Yes. For a suitable HTML file input element, a file path can be supplied using sendKeys().
Q7. What is the difference between clear() and sendKeys()?
clear() removes the existing value from an editable field, while sendKeys() enters text or keyboard input.
Q8. What should you do if sendKeys() gives ElementNotInteractableException?
Check whether the element is visible, enabled, interactable, correctly located, and ready for input. Also check whether another page state, overlay, or frame context is affecting the interaction.
Q9. How can you send CTRL + A?
element.sendKeys(Keys.CONTROL, "a");
Q10. Can sendKeys() be used with XPath?
Yes. XPath can locate the WebElement, after which sendKeys() can be called on that element.
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");
64. Practical Mini Project Using sendKeys()
Create a Selenium automation script for a login and search workflow.
- Launch Chrome.
- Open the application.
- Locate the username field.
- Enter the username using sendKeys().
- Locate the password field.
- Enter the password using sendKeys().
- Click the login button.
- Wait for the home page.
- Locate the search box.
- Enter a product name using sendKeys().
- Press ENTER.
- Validate the search results.
- Close the browser.
Expected automation flow:
Launch Browser
↓
Open Application
↓
Enter Username
↓
Enter Password
↓
Click Login
↓
Wait for Home Page
↓
Enter Search Keyword
↓
Press ENTER
↓
Validate Results
↓
Close Browser
65. Quick Reference
| Requirement | Example |
| Enter text | element.sendKeys("Hello") |
| Press ENTER | element.sendKeys(Keys.ENTER) |
| Press TAB | element.sendKeys(Keys.TAB) |
| Select all | element.sendKeys(Keys.CONTROL, "a") |
| Delete key | element.sendKeys(Keys.DELETE) |
| Backspace | element.sendKeys(Keys.BACK_SPACE) |
| Clear field | element.clear() |
| Upload file | fileInput.sendKeys(filePath) |
| Wait then type | wait.until(...).sendKeys("Text") |
66. Send Keys Best-Practice Checklist
- Identify the correct WebElement.
- Use a stable locator.
- Wait for the element when necessary.
- Check that the element is visible and enabled.
- Clear old values when required.
- Use sendKeys() for normal text input.
- Use the Keys class for special keyboard actions.
- Switch into the correct iframe before interacting with frame elements.
- Use Page Object Model in larger frameworks.
- Keep test data maintainable and reusable.
- Handle dynamic elements with suitable synchronization.
- Use meaningful assertions after important input operations.
67. Conclusion
The sendKeys() method is one of the most frequently used Selenium WebDriver methods for browser automation. It allows automation scripts to enter text, numbers, symbols, keyboard keys, and file paths into appropriate web elements. It is especially useful for login forms, registration forms, search boxes, checkout pages, textareas, and file-upload controls.
For reliable Selenium automation, sendKeys() should be combined with stable locators, appropriate synchronization, proper frame handling, reusable Page Object Model methods, and well-organized test data. Understanding sendKeys() thoroughly helps testers automate realistic user-input workflows and build maintainable Selenium WebDriver test scripts.
Course Resource: Selenium Training Course
Demo Registration: Register for Course Demo